<?php

require_once(sfConfig::get('sf_plugins_dir').'/sfDoctrineGuardPlugin/modules/sfGuardUser/lib/BasesfGuardUserActions.class.php');

/**
 * sfGuardUser actions.
 *
 * @package    sfGuardPlugin
 * @subpackage sfGuardUser
 * @author     Fabien Potencier
 * @version    SVN: $Id: actions.class.php 12896 2008-11-10 19:02:34Z fabien $
 */
class sfGuardUserActions extends BasesfGuardUserActions
{
  protected function initEntity(sfWebRequest $request)
  {
    $entities = array('User' => 'User', 'Store' => 'Store');
    if (empty($this->sf_guard_user)) {
      $parameters = $this->getRequestParameter('sf_guard_user');
      if (isset($parameters['Entity']) && isset($entities[$parameters['Entity']])) {
        $type = $parameters['Entity'];
        unset($parameters['Entity']);
        $request->setParameter('sf_guard_user', $parameters);
      }
    } else {
        $result = Doctrine::getTable('User')->findByUserId($this->sf_guard_user->id);
        $type = $result->count() ? 'User' : 'Store';
    }

    if (isset($type)) {
      $formClass = $type.'Form';
      $form = new $formClass($this->sf_guard_user->$type);
      $object = $form->getObject();
      $fields = $form->getWidgetSchema()->getFields();
      $fields['map']->setDefaults($object->toArray());

      unset($form['id'], $form['user_id']);
      $this->form->embedForm('Entity', $form);
//      $this->form->embedMergeForm('Entity', $form);
    } else {
      $this->form->setWidget('Entity', new sfWidgetFormChoice(array('choices' => $entities)));
    }
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = $this->configuration->getForm();
    $this->sf_guard_user = $this->form->getObject();
    $this->initEntity($request);
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->form = $this->configuration->getForm();
    $this->sf_guard_user = $this->form->getObject();
    $this->initEntity($request);

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->sf_guard_user = $this->getRoute()->getObject();
    $this->form = $this->configuration->getForm($this->sf_guard_user);
    $this->initEntity($request);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->sf_guard_user = $this->getRoute()->getObject();
    $this->form = $this->configuration->getForm($this->sf_guard_user);
    $this->initEntity($request);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }
}
